<?php

namespace App\Models\Plane\PlaneOrderFlight\Repositories;

use App\Models\Plane\PlaneOrderFlight\PlaneOrderFlight;
use App\Models\Plane\PlaneOrderFlight\Repositories\Interfaces\PlaneOrderFlightRepositoryInterface;
use App\Models\Plane\PlaneOrders\PlaneOrder;
use App\Trip\Repository\BaseRepository;

class PlaneOrderFlightRepository extends BaseRepository implements PlaneOrderFlightRepositoryInterface
{
    public function __construct(PlaneOrderFlight $model)
    {
        parent::__construct($model);
    }

    /**
     * @param PlaneOrder $flight_order
     * @param array      $data
     * @return PlaneOrderFlight
     */
    public function addFlight(PlaneOrder $flight_order, array $data): PlaneOrderFlight
    {
        $data['user_id']   = $flight_order->getUserId();
        $data['order_sn']  = $flight_order->getOrderSn();
        $data['current']   = 1;// 当备选行程出票后 current =2
        $data['start_at']  = $data['start_date']." ".$data['start_time'];
        $data['arrive_at'] = $data['arrive_date']." ".$data['arrive_time'];
        if ($res = $this->findFlightByOrder($flight_order)) {
            $this->update($data, $res);
            return $res->refresh();
        }
        return $this->create($data);
    }

    /**
     * @param PlaneOrder $order
     * @return PlaneOrderFlight|null
     */
    public function findFlightByOrder(PlaneOrder $order): ?PlaneOrderFlight
    {
        $data['order_sn'] = $order->getOrderSn();
        $data['user_id']  = $order->getUserId();
        return $this->findOneBy($data);
    }
}